/**
 * 赔偿列表
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useRef, useCallback, useEffect, useMemo } from 'react';
import { useRequest } from '@umijs/hooks';
import { Button, message, Modal } from 'antd';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';
import router from 'umi/router';

import {
  getPkgOrderInfo
} from '../service';
import {
  Const
} from '../../Const';

import AuthComponent from '@/components/Authorized/AuthComponent';

class PrivateData {
  static toolBarRenderArr = [
    { text: '修改', value: '1', authCode: 'basicPermissions' },
    { text: '打印', value: '2', authCode: 'basicPermissions' },
  ];
}

const CompensationList = props => {

  const { modalVisible, onCancel, onSubmit, itemData, ownerType, compensateType, isOnlyPrint } = props;

  const actionRef = useRef();
  const ref = useRef();

  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 勾选索引
  const [selectedRows, setSelectedRows] = useState([]); // 勾选列

  useEffect(() => {
    if (modalVisible) {
      setSelectedRowKeys([]);
      setSelectedRows([]);
    }
  }, [modalVisible]);

  const isBasicPermissions = useMemo(() => {
    return AuthComponent.getAuth(Const.permissionsType.get(ownerType) + '.basicPermissions')
  }, [ownerType]);

  // rowSelection
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys);
    setSelectedRows(selectedRows);
  };
  const rowSelection = {
    type: 'radio',
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  const goToDetail = useCallback(record => {
    onCancel();
    router.push({
      pathname: Const.commonUrl + '/inPortBaggageManagement/compensationDetail',
      state: {
        type: record.compensateType,
        orderId: record.orderId || '',
        ownerType: ownerType
      }
    });
  }, [ownerType]);

  // 顶部点击事件
  const headerTitleClick = useCallback(val => {
    if (val === '1') {
      if (
        selectedRows.length === 1
        && (+selectedRows[0].status === 0 || +selectedRows[0].status === 6)
        && (itemData.status === '处理中' || itemData.status === '待处理')
      ) {
        onCancel();
        router.push({
          pathname: Const.commonUrl + '/inPortBaggageManagement/addEditCompensation',
          state: {
            status: 'edit',
            type: +selectedRows[0].compensateType,
            itemData: selectedRows[0], // 旅客信息
            detailData: selectedRows[0], // 赔偿单信息
            ownerType: ownerType
          }
        });
      } else {
        message.warning('事故单状态为待处理或者处理中，并且是驳回状态的赔偿单才支持修改')
      }
    }
    if (val === '2') {
      if (selectedRows.length === 1) {
        onCancel();
        router.push({
          pathname: Const.commonUrl + '/inPortBaggageManagement/printPeiChang',
          state: {
            orderId: selectedRows[0].orderId || '',
            ownerType: ownerType
          }
        });
      } else {
        message.warning('请选择一个赔偿单')
      }
    }
  }, [selectedRows, ownerType, itemData]);

  const okHandle = useCallback(() => {
    onCancel();
  }, []);

  const columns = [
    {
      title: '赔偿单号',
      dataIndex: 'orderId',
      width: 200,
      hideInSearch: true,
      render: (text, record) => (
        <Button
          type="link"
          disabled={!isBasicPermissions}
          onClick={() => goToDetail(record)}>
          {text}
        </Button>
      )
    },
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '赔偿总价值',
      dataIndex: 'payMoney',
      width: 120,
      hideInSearch: true,
    },
    {
      title: '赔偿原因',
      dataIndex: 'paymentReason',
      width: 300,
      hideInSearch: true,
    },
    {
      title: '支付状态',
      dataIndex: 'receiveStatus',
      width: 100,
      hideInSearch: true,
      filters: false,
      valueEnum: Const.receiveStatusMap,
      render: (text, record) => {
        return record.pkgId ? '-': text;
      }
    },
    {
      title: '审核状态',
      dataIndex: 'status',
      width: 120,
      hideInSearch: true,
      filters: false,
      valueEnum: Const.statusMap,
    },
    {
      title: '审核人',
      dataIndex: 'auditUser',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '批准人',
      dataIndex: 'auditor',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '经手人',
      dataIndex: 'createId',
      width: 100,
      hideInSearch: true,
    },
  ];

  return (
    <Modal
      destroyOnClose
      title="赔偿单"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
    >
      <>
        <ProTable
          actionRef={actionRef}
          formRef={ref}
          className={styles.compactTable}
          rowKey="orderId"
          rowSelection={rowSelection}
          headerTitle="赔偿单列表"
          toolBarRender={() => PrivateData.toolBarRenderArr.map((item, index) => {
            if (index === 0) {
              let isHavePermission = false;
              // 0 临时 1 结案
              if (compensateType === 0) {
                const authCode = Const.permissionsType.get(+ownerType) + '.changeLinShiCompensation';
                if (AuthComponent.getAuth(authCode)) {
                  isHavePermission = true;
                }
              }
              if (compensateType === 1) {
                const authCode = Const.permissionsType.get(+ownerType) + '.changeJieAnCompensation';
                if (AuthComponent.getAuth(authCode)) {
                  isHavePermission = true;
                }
              }
              if (!isOnlyPrint && isHavePermission) {
                return (
                  <AuthComponent authCode={Const.permissionsType.get(+ownerType) + '.' + item.authCode} key={index}>
                    <Button
                      type="primary"
                      onClick={() => headerTitleClick(item.value)}>
                      {item.text}
                    </Button>
                  </AuthComponent>
                )
              }
            } else {
              return (
                <AuthComponent authCode={Const.permissionsType.get(ownerType) + '.' + item.authCode} key={index}>
                  <Button
                    type="primary"
                    onClick={() => headerTitleClick(item.value)}>
                    {item.text}
                  </Button>
                </AuthComponent>
              )
            }
          })}
          request={params => {
            params.accidentId = itemData.accidentId || '';
            params.compensateType = compensateType;
            return getPkgOrderInfo(params);
          }}
          tableAlertRender={false}
          columns={columns}
          options={false}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          }}
          scroll={{ x: 750, y: 240 }}
          search={false}
        >
        </ProTable>
      </>
    </Modal>
  )
};

export default CompensationList;
